package com.hxh.component.business.app;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;

import com.hxh.component.basicore.Base.app.AppDelegate;
import com.hxh.component.basicore.Base.app.IApp;
import com.hxh.component.basicore.Base.app.provider.AppProvider;
import com.hxh.component.basicore.util.Utils;
import com.hxh.component.business.common.UserInfoDTO;
import com.hxh.component.business.utils.Constant;

import static com.hxh.component.basicore.util.Utils.Text.isEmpty;

/**
 * App初始化流程：
 * 1. oncreate委托给AppDelegate去进行一些系统初始化(一般而言，不用动)
 * 2. AppInitDelegate 是进行初始化的地方(初始化你的各种sdk，或者数据之类)
 */
public class App extends Application implements IApp {


    private AppDelegate mAppDelegate;
    private static AppInitDelegate mAppInitDelegate;
    private static Context mContext;

    @Override
    public void onCreate() {

        super.onCreate();
        mContext = this;
        Utils.syncIsDebug(this);

        mAppInitDelegate = new AppInitDelegate(this);
        mAppInitDelegate.init();

        mAppDelegate = new AppDelegate();
        mAppDelegate.onCreate(mAppInitDelegate);
    }


    /**
     * 当程序终止时候
     */
    @Override
    public void onTerminate() {
        super.onTerminate();
        if (null != mAppDelegate) {
            mAppDelegate.onStop();
        }
        mAppInitDelegate = null;
        mAppDelegate = null;
        mContext = null;
    }


    public Application getApplication() {
        return this;
    }

    public static AppInitDelegate getAppInitDelegate() {
        return mAppInitDelegate;
    }

    public static Context getContext() {
        return mContext;
    }

    public static UserInfoDTO getUserDTO() {
        return mAppInitDelegate.getUserDTO();
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    @Override
    public AppProvider getAppComponent() {
        return mAppDelegate.getAppComponent();
    }
}
